<script lang="tsx">
import { defineComponent, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import { ElPagination, ElMessage } from 'element-plus';
import { trimStringParams } from '#/utils/trimStringParams'
import { $t } from '@vben/locales';
import { getCourseInfoForPersonCenterApi } from '#/api/personal';
import { VbenIcon } from '@vben-core/shadcn-ui';
import { SvgCourseIcon, SvgNoDataIcon, CalendarDays } from '@vben/icons';
import { useRouter } from 'vue-router';
import { getImgUrl } from '#/utils/getImgUrl';
import dayjs from 'dayjs'
// baseQuery通过全局注册使用，无需导入

export default defineComponent({
  name: 'PersonalCourses',
  setup() {
    const router = useRouter();
    // 查询数据
    const queryData = reactive({
      name: '',
      status: '',
      participationTime: null
    });

    const pageData = reactive<any>({
      total: 0,
      curPage: 1,
      pageSize: 10
    })

    // 添加缺少的变量
    const loadingFlag = ref([0, 0, 0]); // 加载状态标志
    const tableData = ref([]); // 表格数据
    const loading = ref(false); // 页面加载状态
    const courseImageUrls = ref<Record<string, string>>({}); // 存储课程图片URL

    // 加载课程图片
    const loadCourseImages = async (courses: any[]) => {
      const imagePromises = courses.map(async (course) => {
        if (course.icon && !courseImageUrls.value[course.id]) {
          try {
            const imgData = await getImgUrl(course.icon);
            if (imgData instanceof ArrayBuffer) {
              // 将二进制数据转换为 Blob
              const blob = new Blob([imgData], { type: 'image/png' });
              courseImageUrls.value[course.id] = URL.createObjectURL(blob);
            }
          } catch (err) {
            console.error($t('course.loadImageFail'), err);
            // 静默失败，显示默认图标
          }
        }
      });
      
      // 使用Promise.allSettled确保所有图片加载完成（无论成功或失败）
      await Promise.allSettled(imagePromises);
    };

    // 查询配置
    const queryColumns = [
      {
        prop: 'name',
        label: $t('course.courseName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('course.courseName')]),
        maxlength: 50
      },
      {
        prop: 'status',
        label: $t('common.statusTxt'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('common.statusTxt')]),
        options: [
          { label: $t('course.notStarted'), value: 'not_started' },
          { label: $t('course.learning'), value: 'learning' },
          { label: $t('course.completed'), value: 'completed' }
        ]
      },
      {
        prop: 'participationTime',
        label: $t('course.participationTime'),
        type: 'daterange',
        rangeSeparator: $t('common.rangeSeparatorTxt'),
        startPlaceholder: $t('common.startTimeTxt'),
        endPlaceholder: $t('common.endTimeTxt'),
        'value-format': 'YYYY-MM-DD HH:mm:ss',
        'default-time': [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]
      }
    ];

    // 分页相关方法
    const onSizeChange = (size: number) => {
      pageData.pageSize = size;
      pageData.curPage = 1;
      handleQuery();
    };

    const onCurrentChange = (page: number) => {
      pageData.curPage = page;
      handleQuery();
    };

    // 查询方法
    const handleQuery = () => {
      console.log('查询数据:', queryData);
      const params = {
        curPage: pageData.curPage,
        pageSize: pageData.pageSize
      } as any;
      const trimData = trimStringParams(queryData)
      console.log(trimData)
      Object.keys(trimData).forEach(key => {
        const kVal = trimData[key as keyof typeof trimData]
        if (key === 'participationTime') {
          params.startTime = kVal?.[0]
          params.endTime = kVal?.[1]
        } else if (kVal) {
          params[key] = kVal
        }
      })
      loadingFlag.value[1] = 1;
      console.log(params)

      getCourseInfoForPersonCenterApi(params).then(async (res: any) => {
        let { pageInfo, data = [] } = res
        pageData.total = pageInfo?.totalRows || 0
        tableData.value = data
        // 异步加载课程图片，不阻塞loading状态
        loadCourseImages(data).catch(err => {
          console.error('加载课程图片失败:', err);
        });
      }).finally(() => {
        loadingFlag.value[1] = 0;
      })
    };

    // 重置方法
    const handleReset = () => {
      queryData.name = ''
      queryData.status = ''
      queryData.participationTime = null
      nextTick(() => {
        handleQuery()
      })
    };

    const gotoCourse = (item: any) => {
      router.push({
        path: '/lesson/intro',
        query: {
          courseId: item.id
        }
      })
    }

    const getStatusColor = (status: string) => {
      switch (status) {
        case 'completed':
          return 'bg-[#30A46C]';
        case 'learning':
          return 'bg-[#FFA940]';
        case 'not_started':
          return 'bg-[#8B5CF6]';
        default:
          return 'bg-[#0067D1]';
      }
    }

    const getStatusBgColor = (status: string) => {
      switch (status) {
        case 'completed':
          return 'bg-[#30A46C0D]';
        case 'learning':
          return 'bg-[#FFA9400D]';
        case 'not_started':
          return 'bg-[#8B5CF60D]';
        default:
          return 'bg-[#6B72800D]';
      }
    }

    const getStatusText = (status: string) => {
      switch (status) {
        case 'completed':
          return $t('course.completed');
        case 'learning':
          return $t('course.learning');
        case 'not_started':
          return $t('course.notStarted');
        default:
          return '学习中';
      }
    }

    const getActionText = (status: string) => {
      switch (status) {
        case 'completed':
          return $t('course.viewCourse');
        case 'learning':
          return $t('course.continueStudy');
        case 'not_started':
          return $t('course.enterCourse');
        default:
          return $t('course.enterCourse');
      }
    }

    watch(
      () => loadingFlag.value,
      (val: number[]) => {
        if (val) {
          const isLoading = val.some((i: number) => i === 1)
          loading.value = isLoading
        }
      },
      { deep: true },
    )

    onMounted(() => {
      handleQuery()
    })

    // 组件卸载时清理对象URL
    onUnmounted(() => {
      Object.values(courseImageUrls.value).forEach(url => {
        if (url) {
          URL.revokeObjectURL(url);
        }
      });
    })

    return () => (
      <div class="flex flex-col h-full bg-[#fff] p-[24px] pt-[16px] rounded-[8px]">
        {/* 查询区域 */}
        <div class="border-b border-gray-200 query pb-[6px]">
          <base-query
            columns={queryColumns}
            data={queryData}
            labelPosition="right"
            onClick={handleQuery}
            onReset={handleReset}
          />
        </div>

        {/* 内容区域 */}
        <div class="min-h-[1px] flex-1 overflow-y-auto p-[24px]" v-loading={loading.value}>
          {tableData.value?.length > 0 ? (
            <div class="h-auto grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-[26px]">
              {tableData.value?.map((item: any) => (
                <div key={item.courseId} class={`flex flex-col items-center p-[14px] rounded-[16px] overflow-hidden cursor-pointer hover:shadow-md transition-shadow ${getStatusBgColor(item.status)}`} onClick={() => gotoCourse(item)}>
                  {/* 状态标签 */}
                  <div class="self-start">
                    {/* 状态小圆点 */}
                    <span
                      class={`inline-block w-2 h-2 rounded-full mr-2 align-middle ${getStatusColor(item.status)}`}
                    ></span>
                    <span class="text-sm text-gray-600 mb-2">
                      {getStatusText(item.status)}
                    </span>
                  </div>
                  {/* icon */}
                  {courseImageUrls.value[item.id] ? (
                    <img src={courseImageUrls.value[item.id]} class="w-[88px] h-[88px] object-contain" />
                  ) : (
                    <VbenIcon icon={SvgCourseIcon} class={`w-[88px] h-[88px] fill-transparent`} />
                  )}

                  {/* 卡片内容 */}
                  <div class="text-center pt-[24px] w-full text-[#191919]">
                    {/* 第一行：课程类型-授课老师 */}
                    <div class="text-[14px] font-medium leading-[22px] truncate" title={`${item.name || ''}`}>
                      {item.name || '-'}
                    </div>

                    {/* 第二行：课程名称 */}
                    <div class="text-[14px] leading-[22px] truncate mt-1" title={item.name}>
                      {item.summary || '-'}
                    </div>

                    {/* 第三行：参与时间 */}
                    <div class="text-[14px] leading-[22px] text-[#595959] mt-1">
                      {dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss') || '-'}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div class="w-full h-full flex flex-col items-center justify-center">
              <VbenIcon icon={SvgNoDataIcon} class={`w-[200px] h-[200px] fill-transparent mb-[10px]`} />
              <span class="text-[14px] leading-[22px] text-[#595959]">
                {$t('common.emptyTxt')}
              </span>
            </div>
          )}
        </div>

        {/* 分页区域 */}
        <ElPagination
          class="pagination pt-[15px]"
          size="small"
          layout="total, sizes, prev, pager, next, jumper"
          total={pageData.total}
          v-model:current-page={pageData.curPage}
          v-model:page-size={pageData.pageSize}
          pageSizes={[10, 20, 50, 100]}
          onSize-change={onSizeChange}
          onCurrent-change={onCurrentChange}
        />
      </div>
    );
  }
});
</script>
<style lang="less" scoped></style>
